﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;

namespace IMeiWeiWebService
{
    /// <summary>
    /// PayMent 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消注释以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class PayMentService : System.Web.Services.WebService
    {

        // API URL
        private const string URL = "https://api.pingxx.com/v1/charges/";

        // Key from pingxx
        private const string credentials = "sk_test_Lm5KyPr5G0i1Kqrv54CWjP04";
        // appId from pingxx
        private const string appId = "app_evf1O8Wrbn54eTqz";


        /// <summary>
        ///  Send request - Post Method
        // Send json string to pingxx for create charge
        /// </summary>
        /// <param name="chargeJson"></param>
        /// <returns></returns>
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string CreateCharge(string chargeJson)
        {


            try
            {


                //string orderNO = DateTime.Now.ToFileTime().ToString();
                //string charge = string.Format("{{\n  \"order_no\":{0},\n  \"app\":{{\"id\":\"app_evf1O8Wrbn54eTqz\"}},\n  \"amount\":100,\n  \"channel\":\"alipay_wap\",\n  \"currency\":\"cny\",\n  \"client_ip\":\"127.0.0.1\",\n  \"subject\":\"test\",\n  \"body\":\"dsadasf\",\n  \"metadata\":{{\"color\":\"red\"}},\n  \"description\":\"dsddf\",\n  \"extra\":{{\"success_url\":\"www.baidu.com/success\",\n           \"cancel_url\":\"www.baidu.com/cancel\"}}\n}}", orderNO);

                var response = Util.MakePostRequest(URL, chargeJson, credentials);

                return Util.GetJsonStringFromResponse(response);
                //Console.WriteLine(chargeScucess);


            }
            catch (Exception ex)
            {

                throw;
            }



        }


        /// <summary>
        ///  Send request - Get Method - with Parameter
        ///  返回某个ChargeList
        /// </summary>
        ///   
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

        public string GetCharges()
        {
            try
            {
                string reqString = string.Format("{0}?limit=3", URL);
                var response = Util.MakeGetRequest(reqString, credentials);
                return Util.GetJsonStringFromResponse(response);
                // Console.WriteLine(Util.GetJsonStringFromResponse(response));

            }
            catch (Exception)
            {

                throw;

            }
        }


        // Send request - Get Method
        /// <summary>
        /// 返回某个Charge
        /// </summary>
        /// <param name="chargeId"></param>
        /// 
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string GetCharge(string chargeId)
        {
            try
            {
                string authorization = String.Format("Bearer {0}", credentials);

                // get the charge info by chargeId, such as 'ch_DW94e9Kqzn184u5uDGH400y9'
                string reqString = string.Format("{0}{1}", URL, chargeId);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(reqString);
                request.Method = "Get";

                request.Headers.Add("Authorization", authorization);

                var response = request.GetResponse() as HttpWebResponse;


                return Util.GetJsonStringFromResponse(response);
                //if (response != null && response.StatusCode == HttpStatusCode.OK)
                //{
                //    var charge = Util.GetJsonStringFromResponse(response);
                //    Console.WriteLine(charge);
                //}

            }
            catch (Exception)
            {

                throw;
            }
        }



        /// <summary>
        /// 发起退款流程
        /// </summary>
        /// <param name="chargeId"></param>
        /// <param name="description">退款描述</param>
        /// <returns></returns>
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

        public string CreateRefunds(string chargeId, string description)
        {

            //string authorization = String.Format("Bearer {0}", credentials);

            string reqString = string.Format("{0}{1}/refunds", URL, chargeId);
            //string refund = string.Format("{{\n \"app\":{{\"id\":\"app_evf1O8Wrbn54eTqz\"}},\n \"description\":\"Refund Description\" \n}}");
            string refund = string.Format("{{\n \"description\":\"Refund Description\" \n}}");

            var response = Util.MakePostRequest(reqString, refund, credentials);

            return Util.GetJsonStringFromResponse(response);
            //if (response != null && response.StatusCode == HttpStatusCode.OK)
            //{
            //    var charge = Util.GetJsonStringFromResponse(response);
            //    Console.WriteLine(charge);
            //}

        }


        /// <summary>
        /// 获取一个Charge 的退款交易列表
        /// </summary>
        /// <param name="chargeId"></param>
        /// 

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

        public string GetRefunds(string chargeId)
        {
            try
            {
                string reqString = string.Format("{0}{1}/refunds?limit=3", URL, chargeId);
                var response = Util.MakeGetRequest(reqString, credentials);
                return Util.GetJsonStringFromResponse(response);

            }
            catch (Exception)
            {

                throw;

            }
        }

        /// <summary>
        /// 获取一个退款对象
        /// </summary>
        /// <param name="chargeId"></param>
        /// <param name="refundId"></param>
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

        public string GetRefund(string chargeId, string refundId)
        {
            try
            {
                string authorization = String.Format("Bearer {0}", credentials);

                string reqString = string.Format("{0}{1}/refunds/{2}", URL, chargeId, refundId);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(reqString);
                request.Method = "Get";

                request.Headers.Add("Authorization", authorization);

                var response = request.GetResponse() as HttpWebResponse;

                return Util.GetJsonStringFromResponse(response);

            }
            catch (Exception)
            {

                throw;
            }
        }


    }
}
